package com.flightgame.hibernate;

import java.util.List;
import java.util.StringTokenizer;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.flightgame.tools.Utils;

public class OwnershipDao {
	@Autowired
	private SessionFactory sessionFactory;
	@Autowired
	private AirportDao airportDao;
	
	@Transactional
	public void addOwnership(Ownership ownership){
		try{
			sessionFactory.getCurrentSession().persist(ownership);
			}
		catch(Exception sq){
			sq.printStackTrace();
		}
	}
	
    @SuppressWarnings("unchecked")
	public List<Ownership> getOwnerships(){
		return sessionFactory.getCurrentSession().createQuery("from Ownership").list();
	}
    
    @SuppressWarnings("unchecked")
    public List<Ownership> getUserOwnerships(String username){
    	return sessionFactory.getCurrentSession().createQuery("from Ownership where username =:username").setParameter("username",username).list();
    }
    
    public Ownership getOwnership(int id){
    	return (Ownership) sessionFactory.getCurrentSession().createQuery("from Ownership where id =:id").setParameter("id",id).uniqueResult();
    }
    
    @SuppressWarnings("unchecked")
    public List<Ownership> getOwnershipsOnBoundedCoordinates(double lat1,double lat2,double lon1,double lon2){
    	return sessionFactory.getCurrentSession().createQuery("from Ownership where  lat > :lat1 AND lat < :lat2 AND lon > :lon1 AND lon < :lon2").setDouble("lat1",lat1).setDouble("lat2",lat2).setDouble("lon1",lon1).setDouble("lon2",lon2).list();
    }
    
    @Transactional
    public void setOwnershipParam(int ownershipId,String param,String value){
    	Ownership ownership = getOwnership(ownershipId);
    	Utils util = new Utils();
    	
    	String params = util.setParameterValue(ownership.getParams(),param,value);
    	ownership.setParams(params);
    	
    	sessionFactory.getCurrentSession().update(ownership);
    }
    
    @Transactional
    public void changeOwnershipUsername(int ownershipId,String newUsername){
    	Ownership ownership = getOwnership(ownershipId);
    	
    	ownership.setUsername(newUsername);
    	sessionFactory.getCurrentSession().update(ownership);
    }
    
    @Transactional
    public void changeAircraftAirport(int ownershipId,String airportCode){
    	Ownership ownership = getOwnership(ownershipId);
    	
    	ownership.setAirportcode(airportCode);
    	Airport airport = airportDao.getAirportByCode(airportCode);
    	ownership.setLat(airport.getLat());
    	ownership.setLon(airport.getLon());
    	
    	sessionFactory.getCurrentSession().update(ownership);
    }
    
    public String getOwnershipParam(int ownershipId,String param){
    	Ownership ownership = getOwnership(ownershipId);
    	Utils util = new Utils();
    	return util.getParameterValue(ownership.getParams(), param);
    }
}
